package com.xuecheng.content.service.iml;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.service.TeachplanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 课程计划
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TeachplanServiceIml implements TeachplanService {

    private final TeachplanMapper teachplanMapper;

    private final TeachplanMediaMapper teachplanMediaMapper;
    /**
     * 查询课程计划信息
     * @param id
     * @return
     */
    @Override
    public List<TeachplanDto> queryTeachplanTreeNodes(Long id) {
        List<TeachplanDto> teachplanDtos = teachplanMapper.queryTeachplanTreeNodes(id);
        //查询无子节点的数据
        Set<Long> collect = teachplanDtos.stream().map(TeachplanDto::getId).collect(Collectors.toSet());
        List<TeachplanDto> teachplanDtos1 = teachplanMapper.selectListById(id);
        for(TeachplanDto teachplanDto :teachplanDtos1){
            if(collect.add(teachplanDto.getId())){
                teachplanDtos.add(teachplanDto);
            }
        }
        log.info("{}",teachplanDtos);
        return teachplanDtos;
    }

    /**
     * 新增课程计划--章
     * @param saveTeachplanDto
     */
    @Override
    public void saveTeachplanTreeNodesZhang(SaveTeachplanDto saveTeachplanDto) {
        Long id = saveTeachplanDto.getId();

        //课程标识为空时
        if(saveTeachplanDto.getCourseId()==null){
            throw new XueChengPlusException("课程标识为空");
        }
        //父亲节点为空
        if(saveTeachplanDto.getParentid()==null){
            throw new XueChengPlusException("父亲节点为空");
        }
        //层级为空
        if(saveTeachplanDto.getGrade()==null) {
            throw new XueChengPlusException("层级为空");
        }
        Teachplan teachplan = BeanUtil.copyProperties(saveTeachplanDto, Teachplan.class);
        teachplan.setCreateDate(LocalDateTime.now());
        //新增
        if(id==null){
            //获取排序号
            int count =getOrderby(saveTeachplanDto.getCourseId(),saveTeachplanDto.getParentid());
            //课程状态标记为正常
            teachplan.setStatus(1);
            teachplan.setOrderby(count+1);
            int i = teachplanMapper.insert(teachplan);
            Teachplan teachplan1 = teachplanMapper.selectById(teachplan);
            if(i<=0){
                throw new XueChengPlusException("新增课程计划失败");
            }
        }else {
            //更新
            int i = teachplanMapper.updateById(teachplan);
            if(i<=0){
                throw new XueChengPlusException("更新课程计划失败");
            }
        }


    }

    @Override
    public void deleteTeachplan(Long id) {
        //判断课程计划下有无子目录
        LambdaQueryWrapper<Teachplan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Teachplan::getParentid,id);
        Integer count = teachplanMapper.selectCount(wrapper);
        if(count>0){
            throw new XueChengPlusException("课程计划信息还有子级信息，无法操作");
        }
        //删除课程计划
        int i = teachplanMapper.deleteById(id);
        if(i<=0){
            throw new XueChengPlusException("删除失败");
        }
    }

    /**
     * 向下移动课程计划
     * @param id
     */
    @Override
    public void moveDownTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        //获取下一个课程计划
        LambdaQueryWrapper<Teachplan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Teachplan::getCourseId,teachplan.getCourseId());
        wrapper.eq(Teachplan::getOrderby,teachplan.getOrderby()+1);
        Teachplan teachplanDown = teachplanMapper.selectOne(wrapper);
        if(teachplanDown==null){
            throw new XueChengPlusException("下方没有课程计划");
        }
        //更新排序
        Integer t1=teachplan.getOrderby();
        Integer t2 = teachplanDown.getOrderby();
        teachplan.setOrderby(t2);
        teachplanDown.setOrderby(t1);
        int i = teachplanMapper.updateById(teachplan);
        teachplanMapper.updateById(teachplanDown);
    }

    /**
     * 向上移动课程计划
     * @param id
     */
    @Override
    public void moveUpTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        //获取下一个课程计划
        LambdaQueryWrapper<Teachplan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Teachplan::getCourseId,teachplan.getCourseId());
        wrapper.eq(Teachplan::getOrderby,teachplan.getOrderby()-1);
        Teachplan teachplanDown = teachplanMapper.selectOne(wrapper);
        if(teachplanDown==null){
            throw new XueChengPlusException("上方没有课程计划");
        }
        //更新排序
        Integer t1=teachplan.getOrderby();
        Integer t2 = teachplanDown.getOrderby();
        teachplan.setOrderby(t2);
        teachplanDown.setOrderby(t1);
        int i = teachplanMapper.updateById(teachplan);
        teachplanMapper.updateById(teachplanDown);
    }

    /**
     * 课程计划和媒资信息绑定
     * @param bindTeachplanMediaDto
     */
    @Override
    public void associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan==null){
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
        //课程id
        Long courseId = teachplan.getCourseId();

        //先删除原来该教学计划绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachplanId));

        //再添加教学计划与媒资的绑定关系
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);
    }

    /**
     * 删除课程计划和媒资信息绑定
     * @param teachPlanId
     * @param mediaId
     */
    @Override
    public void deleteAssociationMedia(Long teachPlanId, String mediaId) {
        LambdaQueryWrapper<TeachplanMedia> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TeachplanMedia::getTeachplanId,teachPlanId)
                .eq(TeachplanMedia::getMediaId,mediaId);
        teachplanMediaMapper.delete(wrapper);
    }


    /**
     * 获取排序号
     * @param courseId
     * @param parentid
     * @return
     */
    private int getOrderby(Long courseId,Long parentid) {
        QueryWrapper<Teachplan> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Teachplan::getCourseId,courseId);
        return teachplanMapper.selectCount(wrapper);
    }
}
